package com.lut.liuning.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;


@Configuration
public class ShiroConfig {
    // 3 设置安全管理器
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);

        /*
        anno：无需认证就可以访问
        authc：必须认证了才可以访问
        user：必须有 记住我 功能才可以使用
        perms：拥有对某个资源的权限才可以访问
        role：拥有某个角色才可以访问
         */

        //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();
        //filterMap.put("/user/*","authc");
        //授权
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");


        filterFactoryBean.setFilterChainDefinitionMap(filterMap);
        //设置登录的请求
        filterFactoryBean.setLoginUrl("/toLogin");
        //设置未授权的请求
        filterFactoryBean.setUnauthorizedUrl("/noauth");
        return filterFactoryBean;
    }
    // 2 DefaultWebSecurityManager
    @Bean
    public SecurityManager securityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    // 1 创建realm对象，自定义类
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //整合shiro和thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
